<template>
  <div>
    <customDialog
      :title="`${title}分销商`"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @confirm="confirmDialog(ruleFormRef)"
      width="800"
    >
      <div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-position="right"
          label-width="80px"
          class="form_box"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="企业名称" prop="name">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入企业名称"
                  maxlength="25"
                  show-word-limit
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="企业编码" prop="code">
                <el-input
                  v-model="formData.code"
                  placeholder="请输入企业编码"
                  clearable
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="姓名" prop="realName">
                <el-input
                  v-model="formData.realName"
                  placeholder="请输入姓名"
                  clearable
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="formData.phone"
                  placeholder="请输入手机号"
                  clearable
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="账号" prop="userName">
                <el-input
                  v-model="formData.userName"
                  placeholder="请输入账号"
                  clearable
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="formData.email"
                  placeholder="请输入邮箱"
                  clearable
                  maxlength="28"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row />
          <el-row>
            <el-col :span="24">
              <el-form-item label="说明" prop="description">
                <el-input
                  v-model="formData.description"
                  placeholder="说明"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  clearable
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customDialog from "@/components/CustomDialog/index.vue";
import { getTenant } from "@/api/auth/index";
import { addTenant, updateTenant } from "@/api/operateCenter/distributor/index";
import type { FormInstance } from "element-plus";
import { cloneDeep, debounce } from "lodash-es";

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const form = {
  id: "",
  name: "",
  code: "",
  realName: "",
  userName: "",
  phone: "",
  email: "",
  description: "",
};
const formData = ref(Object.assign({}, form));

const title = ref<string>("");

const validataEmail = (rule: any, value: any, callback: any) => {
  // 匹配包含数字、字母或者字符的8-16位正则表达式
  let reg =
    /^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
  if (value && !reg.test(value)) {
    callback(new Error("请输入有效的邮箱地址"));
  } else {
    callback();
  }
};

const rules = reactive({
  name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  userName: [
    { required: true, message: "请输入账号,建议使用手机号码", trigger: "blur" },
  ],
  phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
  email: [{ required: false, validator: validataEmail, trigger: "blur" }],
});

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl?.resetFields();
  Object.assign(formData.value, form);
  dialogVisible.value = false;
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let URL;
      if (title.value == "编辑") {
        URL = updateTenant;
      } else {
        URL = addTenant;
      }
      formData.value.code = formData.value.userName;
      URL(formData.value).then(() => {
        ElMessage.success(`${title.value}成功`);
        dialogVisible.value = false;
        emit("success");
        closeDialog(ruleFormRef.value);
      });
    }
  });
}, 150);

const getInfo = (val: Record<string, any>) => {
  getTenant(val.id).then((res: Record<string, any>) => {
    formData.value.id = res.data.id;
    formData.value.name = res.data.name;
    formData.value.realName = res.data.realName;
    formData.value.userName = res.data.userName;
    formData.value.phone = res.data.phone;
    formData.value.email = res.data.email;
    formData.value.description = res.data.description;
    formData.value.code = res.data.code;
  });
};

// 父级电子显示dialog
const showDialog = async (val: any) => {
  // console.log("显示弹窗----", val);
  dialogVisible.value = true;
  title.value = val ? "编辑" : "新增";
  if (val) {
    getInfo(val);
  }
};

defineExpose({
  showDialog,
});
</script>

<style scoped lang="scss">
.form_box {
  padding: 0 20px;
}
</style>
